docker runするときに複数行のShellをファイルを使わずに実行させたい - ヒアドキュメントを使う
やりたくなった理由
必要だった理由が、CircleCIのVMがUbuntu(Trusty)で、curl --http2を使うためには、CI中にcurlをビルドするとかの方法が浮かんだが、それだと時間がかかってしまうため、ubuntu:18.04のDockerイメージを使って、HTTP/2に対応のcurlをコンテナ内部で使った。なおかつ一時ファイルなどを作りたくなかった。 シンプルな例
以下の例では、ls -lをubuntu:18.04内で、実行している。
code:bash
docker run --rm -i ubuntu:18.04 /bin/bash << EOF
ls -l
EOF
code:結果
total 64
drwxr-xr-x 2 root root 4096 Mar 7 21:01 bin
drwxr-xr-x 2 root root 4096 Apr 24 2018 boot
drwxr-xr-x 5 root root 340 Mar 22 10:32 dev
drwxr-xr-x 1 root root 4096 Mar 22 10:32 etc
drwxr-xr-x 2 root root 4096 Apr 24 2018 home
drwxr-xr-x 8 root root 4096 May 23 2017 lib
drwxr-xr-x 2 root root 4096 Mar 7 21:00 lib64
drwxr-xr-x 2 root root 4096 Mar 7 21:00 media
drwxr-xr-x 2 root root 4096 Mar 7 21:00 mnt
drwxr-xr-x 2 root root 4096 Mar 7 21:00 opt
dr-xr-xr-x 209 root root 0 Mar 22 10:32 proc
drwx------ 2 root root 4096 Mar 7 21:01 root
drwxr-xr-x 1 root root 4096 Mar 12 00:20 run
drwxr-xr-x 1 root root 4096 Mar 12 00:20 sbin
drwxr-xr-x 2 root root 4096 Mar 7 21:00 srv
dr-xr-xr-x 13 root root 0 Mar 22 10:32 sys
drwxrwxrwt 2 root root 4096 Mar 7 21:01 tmp
drwxr-xr-x 1 root root 4096 Mar 7 21:00 usr
drwxr-xr-x 1 root root 4096 Mar 7 21:01 var
exit codeはホストにも伝わる
code:bash
docker run --rm -i ubuntu:18.04 /bin/bash << EOF
ls -l
exit 123
EOF
echo $?
# => 123
実際の例
以下は複数書けることを示す実際の例。
code:bash
# HTTP/2 test in Docker container
docker run --rm -i -e server_host=$server_host ubuntu:18.04 /bin/bash << EOF
set -xeu
apt update
apt install -y curl
# Get help
curl --http2 ${server_host}:8080/help
# Create a file to send
echo 'hello, world' > /tmp/hello.txt
# Send and wait for a reciever
curl --http2 -T /tmp/hello.txt ${server_host}:8080/mypath &
# Get data as a file
curl --http2 ${server_host}:8080/mypath > /tmp/download.txt
# Print downloaded file
cat /tmp/download.txt
# Test the equality
diff /tmp/hello.txt /tmp/download.txt
rm /tmp/download.txt
EOF
以下が実際にやっている行